import 'package:aweb5/Constants.dart';
import 'package:aweb5/bean/aplus/phone_code_entity.dart';
import 'package:aweb5/generated/json/member_info_entity_helper.dart';
import 'package:aweb5/generated/json/phone_code_entity_helper.dart';
import 'package:aweb5/generated/json/registery_entity_helper.dart';
import 'package:aweb5/generated/json/tuijianren_entity_helper.dart';
import 'package:aweb5/pages/AplusHomePage.dart';
import 'package:aweb5/util/DialogUtil.dart';
import 'package:aweb5/util/JsonUtil.dart';
import 'package:aweb5/util/toast_util.dart';
import 'package:aweb5/widgetlib/LoginFormCode.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:aweb5/util/StringUtil.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
//import 'package:fluttertoast/fluttertoast.dart';
import 'package:aweb5/config/Config.dart';
import 'package:aweb5/util/HttpClient.dart';
import 'package:aweb5/bean/aplus/member_info_entity.dart';
import 'package:aweb5/util/SharedUtil.dart';
import 'package:aweb5/util/DateUtil.dart';
import 'package:aweb5/util/NaviUtil.dart';
import 'package:load/load.dart';
import 'package:aweb5/style.dart';
import 'package:aweb5/bean/aplus/tuijianren_entity.dart';
import 'package:aweb5/bean/aplus/registery_entity.dart';
class AplusRegistery extends StatefulWidget {
  @override
  _AplusRegisteryState createState() => _AplusRegisteryState();
}

class _AplusRegisteryState extends State<AplusRegistery> {
  TextEditingController accountController = TextEditingController();
  TextEditingController passwordController = TextEditingController();
  TextEditingController nameController = TextEditingController();

  bool hasSendCode = false;
  Function callBack;

  String avatar = "";

  String tuijianrenName = "";

  String tuijianrenId = "";
  BuildContext context;
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    this.callBack = requestCode;
    WidgetsBinding.instance.addPostFrameCallback((timeStamp) {requestTuijianrenInfo();});

  }

  @override
  Widget build(BuildContext context) {
    this.context =context;
    return Scaffold(
      body: buildBody(context),
    );
  }

  Widget buildBody(BuildContext context) {
    return Container(
      width: MediaQuery.of(context).size.width,
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.center,
        children: <Widget>[
          Expanded(
            child: Text(""),
            flex: 6,
          ),
          Container(
            child: Image.asset(
              "assets/jjhw.png",
              height: 60,
              width: 150,
              fit: BoxFit.fill,
            ),
          ),
          Expanded(
            child: Text(""),
            flex: 2,
          ),
          Container(
            padding: EdgeInsets.symmetric(vertical: 3, horizontal: 10),
            child: Text(
              "用心体验过的极好物品",
              style: TextStyle(color: Color(0xfff64269), fontSize: 12),
            ),
            decoration: BoxDecoration(
                border: Border.all(color: Color(0xfff64269)),
                borderRadius: BorderRadius.circular(5)),
          ),
          Expanded(
            child: Text(""),
            flex: 5,
          ),
          Container(
            alignment: Alignment.centerLeft,
            height: 35,
            margin: EdgeInsets.only(left: 50, right: 50),
            decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(5),
                color: Color(0xfff2f2f2)),
            child: Row(
              children: <Widget>[
                Expanded(
                  child: TextField(
                    controller: accountController,
                    keyboardType: TextInputType.number,
                    decoration: InputDecoration(
                      hintText: "请输入手机号",
                      hintStyle: TextStyle(
                        color: Color(0xffa1a1a1),
                        fontSize: 12,
                      ),
                      border: InputBorder.none,
                      contentPadding: EdgeInsets.only(left: 10.0, bottom: 10),
                    ),
                  ),
                ),
                InkWell(
                  child: Container(
                    width: 30,
                    height: 30,
                    padding: EdgeInsets.all(5),
                    child: Image.asset("assets/assist/guanbi1.png"),
                  ),
                  onTap: () {
                    accountController.clear();
                  },
                )
              ],
            ),
          ),
          SizedBox(
            height: 20,
          ),
          Container(
              alignment: Alignment.centerLeft,
              height: 35,
              margin: EdgeInsets.only(left: 50, right: 50),
              decoration: BoxDecoration(
                  borderRadius: BorderRadius.circular(5),
                  color: Color(0xfff2f2f2)),
              child: Row(
                crossAxisAlignment: CrossAxisAlignment.center,
                children: <Widget>[
                  Expanded(
                      child: TextField(
                    controller: passwordController,
                    obscureText: false,
                    keyboardType: TextInputType.number,
                    decoration: InputDecoration(
                        hintText: "请入验证码",
                        hintStyle: TextStyle(
                          color: Color(0xffa1a1a1),
                          fontSize: 12,
                        ),
                        border: InputBorder.none,
                        contentPadding: EdgeInsets.only(left: 10, bottom: 10)),
                  )),
                  InkWell(
                    child: Container(
                      width: 25,
                      height: 25,
                      padding: EdgeInsets.all(5),
                      child: Image.asset("assets/assist/guanbi1.png"),
                    ),
                    onTap: () {
                      passwordController.clear();
                    },
                  ),
                  Container(
                    alignment: Alignment.center,
                    width: 100,
                    height: 35,
                    child: LoginFormCode(
                      textEditingController: accountController,
                      onTapCallback: callBack,
                    ),
                  )
                ],
              )),
          SizedBox(
            height: 20,
          ),
          Container(
            alignment: Alignment.centerLeft,
            height: 35,
            margin: EdgeInsets.only(left: 50, right: 50),
            decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(5),
                color: Color(0xfff2f2f2)),
            child: Row(
              children: <Widget>[
                Expanded(
                  child: TextField(
                    controller: nameController,
                    keyboardType: TextInputType.number,
                    decoration: InputDecoration(
                      hintText: "请输入姓名",
                      hintStyle: TextStyle(
                        color: Color(0xffa1a1a1),
                        fontSize: 12,
                      ),
                      border: InputBorder.none,
                      contentPadding: EdgeInsets.only(left: 10.0, bottom: 10),
                    ),
                  ),
                ),
                InkWell(
                  child: Container(
                    width: 30,
                    height: 30,
                    padding: EdgeInsets.all(5),
                    child: Image.asset("assets/assist/guanbi1.png"),
                  ),
                  onTap: () {
                    nameController.clear();
                  },
                )
              ],
            ),
          ),
          SizedBox(
            height: 20,
          ),
          Container(
            alignment: Alignment.centerLeft,
            margin: EdgeInsets.only(left: 50, right: 50),
            child: Row(
              children: <Widget>[
                Text("推荐人"),
                SizedBox(
                  width: 20,
                ),
                CircleAvatar(
                  backgroundColor: Colors.white,
                  radius: 26.0,
                  backgroundImage: avatar.isEmpty
                      ? AssetImage("assets/assist/aplus.png")
                      : NetworkImage(avatar),
                ),
                Expanded(child: Text(tuijianrenName)),
                GestureDetector(
                  child: Container(
                    padding: EdgeInsets.symmetric(vertical: 5, horizontal: 10),
                    decoration: redButtonStyle,
                    alignment: Alignment.center,
                    child: Text(
                      "更新",
                      style: TextStyle(color: Colors.white),
                    ),
                  ),
                  onTap: () {
                    _showTuijianren();
                  },
                )
              ],
            ),
          ),
          SizedBox(
            height: 20,
          ),
          GestureDetector(
            child: Container(
              margin: EdgeInsets.only(left: 50, right: 50, top: 30),
              height: 35,
              decoration: BoxDecoration(
                  color: Color(0xfff64269),
                  borderRadius: BorderRadius.circular(5)),
              child: Center(
                child: Text(
                  "注册",
                  style: TextStyle(fontSize: 18, color: Colors.white),
                ),
              ),
            ),
            onTap: () {
              if (!StringUtil.isPhone(accountController.text)) {
//                Fluttertoast.showToast(msg: "请输入正确的手机号");
                Toast.show(msg: "请输入正确的手机号");
                return;
              }
              if (passwordController.text.isEmpty) {
//                Fluttertoast.showToast(msg: "请输入验证码");
                Toast.show(msg: "请输入验证码");
                return;
              }
              if (nameController.text.isEmpty) {
//                Fluttertoast.showToast(msg: "请点击发送验证码");
                Toast.show(msg: "请输入姓名");
                return;
              }
              requestRegistery();
//              request();
            },
          ),
          Expanded(
            child: Text(""),
            flex: 10,
          ),
        ],
      ),
    );
  }

  void call(String id,String name,String avatar){
    this.tuijianrenId = id;
    this.tuijianrenName = name;
    this.avatar = avatar;
    setState(() {

    });
  }

  void _showTuijianren() {
    showModalBottomSheet(
        context: context,
        isScrollControlled: true,
        builder: (c) {
          return

            SizedBox(

              height: ScreenUtil().setHeight(350),
              child: Tuijianren(call),
            )
            ;
        });
  }

  void requestCode() async {
    hasSendCode = true;
    try {
      Map<String, dynamic> map = Map<String, dynamic>();
      map["mobile"] = accountController.text;

      Map<String, dynamic> map1 = await HttpClient.requestLogin(
          Config.requestApi + 'member/login/sendSms',
          data: map);

      PhoneCodeEntity loginEntity = new PhoneCodeEntity();

      loginEntity = phoneCodeEntityFromJson(loginEntity, map1);

      if (loginEntity.code == null) {
//        Fluttertoast.showToast(msg: "null");
        return;
      }
      if (loginEntity.code == 200) {}
    } catch (e) {
      print(e.toString());
    }
  }

   void requestLogin() async {

    DialogUtil.showloadingdialog(context);
    try {
      Map<String, dynamic> map = Map<String, dynamic>();
      map["mobile"] = accountController.text;
      map["smscode"] = passwordController.text;

      Map<String, dynamic> map1 = await HttpClient.requestLogin(
          Config.requestApi + 'member/login/index',
          data: map);

      MemberInfoEntity memberInfoEntity = new MemberInfoEntity();
      memberInfoEntity = memberInfoEntityFromJson(memberInfoEntity, map1);
      DialogUtil.pop(context);
      if (memberInfoEntity.code == null) {
        return;
      }

      if (memberInfoEntity.code == 200) {
        SharedUtil.addStr(Constants.MEMBER_INFO, JsonUtil.map2json(map1));
        SharedUtil.addStr(Constants.LAST_LOGIN_TIME, DateTime.now().toString());
        Constants.memberInfoEntity = memberInfoEntity;

        NaviUtil.pushAndRemove(context,
            HomePage(Constants.memberInfoEntity.data.memberId.toString()));
      }
    } catch (e) {
      print(e.toString());
    } finally {

      DialogUtil.pop(context);
      print(">>>>>finally111111");
    }
  }

//注册
  void requestRegistery() async {

    DialogUtil.showloadingdialog(context);
    try {
      Map<String, dynamic> map = Map<String, dynamic>();
      map["mobile"] = accountController.text;
      map["smscode"] = passwordController.text;
      map["name"] = nameController.text;
      map["parent_id"] = tuijianrenId;

      Map<String, dynamic> map1 = await HttpClient.requestLogin(
          Config.requestApi + 'member/login/register',
          data: map);

      RegisteryEntity memberInfoEntity = new RegisteryEntity();
      memberInfoEntity = registeryEntityFromJson(memberInfoEntity, map1);
      DialogUtil.pop(context);
      if (memberInfoEntity.code == null) {
        return;
      }

      if (memberInfoEntity.code == 200) {
        Toast.show(msg: "注册成功");

        NaviUtil.pop(context);

      } else{
        Toast.show(msg: memberInfoEntity.msg);
      }
    } catch (e) {
      print(e.toString());
    } finally {

      DialogUtil.pop(context);
      print(">>>>>finally111111");
    }
  }

  void requestTuijianrenInfo() async {
    DialogUtil.showloadingdialog(context);
     try {
      Map<String, dynamic> map = Map<String, dynamic>();
      map["mobile"] = "";
      map["is_first"] = 1;

      Map<String, dynamic> map1 = await HttpClient.requestLogin(
          Config.requestApi + 'member/login/info',
          data: map);

      TuijianrenEntity loginEntity = new TuijianrenEntity();

      loginEntity = tuijianrenEntityFromJson(loginEntity, map1);

      DialogUtil.pop(context);
      if (loginEntity.code == null) {
//        Fluttertoast.showToast(msg: "null");
        Toast.show(msg: loginEntity.msg);
        return;
      }
      if (loginEntity.code == 200) {

        tuijianrenName = loginEntity.data.nickname;
        avatar = loginEntity.data.headimgurl;
        tuijianrenId = loginEntity.data.id.toString();
        setState(() {

        });

      }
    } catch (e) {
      print(e.toString());

      DialogUtil.pop(context);
    }
  }

}

class Tuijianren extends StatefulWidget {
  Function call;
  Tuijianren(this.call);
  @override
  _TuijianrenState createState() => _TuijianrenState();
}

class _TuijianrenState extends State<Tuijianren> {
  String avatar = "";
  String name = "";
  String id = "";
  TextEditingController editingController = TextEditingController();
  BuildContext context;
  @override
  Widget build(BuildContext context) {
    this.context = context;
    return Scaffold(
      body: Container(
        padding: EdgeInsets.all(ScreenUtil().setHeight(20)),
        child: Column(
          children: <Widget>[
            Row(
              children: <Widget>[
                Expanded(
                    child: Center(
                  child: Text("   您将绑定推荐人"),
                )),
                GestureDetector(
                  child: Image.asset(
                    "assets/assist/guanbib.png",
                    width: ScreenUtil().setWidth(20),
                    height: ScreenUtil().setHeight(20),
                  ),
                  onTap: () {
                    NaviUtil.pop(context);
                  },
                )
              ],
            ),
            SizedBox(
              height: ScreenUtil().setHeight(10),
            ),
            Container(
              width: ScreenUtil().setWidth(50),
              height: ScreenUtil().setHeight(50),
              child: CircleAvatar(
                radius: ScreenUtil().setHeight(25),
                backgroundImage: avatar.isEmpty
                    ? AssetImage("assets/assist/aplus.png")
                    : NetworkImage(avatar),
              ),
            ),
            Text(name),
            SizedBox(
              height: ScreenUtil().setHeight(10),
            ),
            Text(id.isNotEmpty?"id:${id}":""),
            SizedBox(
              height: ScreenUtil().setHeight(10),
            ),
            Text("请仔细核对绑定推荐人信息",style: TextStyle(color: Colors.grey),),
            SizedBox(
              height: ScreenUtil().setHeight(20),
            ),
            Row(
              children: <Widget>[
                Expanded(
                    child: Container(
                      decoration: BoxDecoration(borderRadius: BorderRadius.circular(10),border: Border.all(color: Colors.grey)),

                  height: ScreenUtil().setHeight(40),
                  child: TextField(
                    controller: editingController,
                    decoration: InputDecoration(border: InputBorder.none),

                  ),


                )),
                SizedBox(
                  width: ScreenUtil().setWidth(5),
                ),
                GestureDetector(
                  child: Container(
                    height: ScreenUtil().setHeight(40),
                    padding: EdgeInsets.symmetric(horizontal: ScreenUtil().setWidth(10)),
                    decoration: redButtonStyle,
                    alignment: Alignment.center,
                    child: Text(
                      "更新",
                      style: TextStyle(color: Colors.white),
                    ),
                  ),
                  onTap: () {

                    if(editingController.text.isEmpty){
                      Toast.show(msg: "请填写推荐人手机号码");
                      return;
                    }
                    requestTuijianrenInfo();

                  },
                )
              ],
            ),
            Expanded(
              child: Text(""),
            ),
            GestureDetector(
              child: Container(
                height: ScreenUtil().setHeight(40),
                decoration: redButtonStyle,
                margin:
                EdgeInsets.symmetric(horizontal: ScreenUtil().setWidth(2)),
                alignment: Alignment.center,
                child: Text(
                  "绑定推荐人",
                  style: TextStyle(color: Colors.white),
                ),
              ),
              onTap: (){

                if(id.isEmpty){
                  Toast.show(msg: "请先获取推荐人");
                  return;
                }
                widget.call(id,name,avatar);
                NaviUtil.pop(context);

              },

            )
            ,
          ],
        ),
      ),
      resizeToAvoidBottomPadding: true,
    );
  }
//推荐人信息
  void requestTuijianrenInfo() async {

    DialogUtil.showloadingdialog(context);
    try {
      Map<String, dynamic> map = Map<String, dynamic>();
      map["mobile"] = editingController.text;
      map["is_first"] = 0;

      Map<String, dynamic> map1 = await HttpClient.requestLogin(
          Config.requestApi + 'member/login/info',
          data: map);

      TuijianrenEntity loginEntity = new TuijianrenEntity();

      loginEntity = tuijianrenEntityFromJson(loginEntity, map1);

DialogUtil.pop(context);
if (loginEntity.code == null) {
//        Fluttertoast.showToast(msg: "null");
        Toast.show(msg: loginEntity.msg);
        return;
      }
      if (loginEntity.code == 200) {

        name = loginEntity.data.nickname;
        avatar = loginEntity.data.headimgurl;
        id = loginEntity.data.id.toString();
        setState(() {

        });

      }
    } catch (e) {
      print(e.toString());
      DialogUtil.pop(context);

    }
  }
}
